<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/facicon.ico?v=5.1.4" color="#222">





  <meta name="keywords" content="Java,">





  <link rel="alternate" href="/atom.xml" title="Key" type="application/atom+xml">






<meta name="description" content="java String类的基本特点 String类的两种实例化方法几乎所有的项目开发过程之中都一定会有String类的使用，但是String类的定义有一些差别，在使用上是有一些注意事项的。 String可以采用直接赋值的方式进行处理，这一点感觉上是和我们的基本数据类型是非常相似的。 范例：直接赋值实例化对象 12345678//字符串的直接赋值public class String1&amp;#123;">
<meta name="keywords" content="Java">
<meta property="og:type" content="article">
<meta property="og:title" content="Java String类的基本特点">
<meta property="og:url" content="https://blog.qipo.net/2018/01/27/java/index.html">
<meta property="og:site_name" content="Key">
<meta property="og:description" content="java String类的基本特点 String类的两种实例化方法几乎所有的项目开发过程之中都一定会有String类的使用，但是String类的定义有一些差别，在使用上是有一些注意事项的。 String可以采用直接赋值的方式进行处理，这一点感觉上是和我们的基本数据类型是非常相似的。 范例：直接赋值实例化对象 12345678//字符串的直接赋值public class String1&amp;#123;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://assets.qipo.net/String1.PNG">
<meta property="og:image" content="http://assets.qipo.net/string2.PNG">
<meta property="og:image" content="http://assets.qipo.net/string3.PNG">
<meta property="og:image" content="http://assets.qipo.net/string4.PNG">
<meta property="og:image" content="http://assets.qipo.net/string5.PNG">
<meta property="og:image" content="http://assets.qipo.net/string6.PNG">
<meta property="og:updated_time" content="2020-06-04T08:30:16.904Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java String类的基本特点">
<meta name="twitter:description" content="java String类的基本特点 String类的两种实例化方法几乎所有的项目开发过程之中都一定会有String类的使用，但是String类的定义有一些差别，在使用上是有一些注意事项的。 String可以采用直接赋值的方式进行处理，这一点感觉上是和我们的基本数据类型是非常相似的。 范例：直接赋值实例化对象 12345678//字符串的直接赋值public class String1&amp;#123;">
<meta name="twitter:image" content="http://assets.qipo.net/String1.PNG">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.qipo.net/2018/01/27/java/">





  <title>Java String类的基本特点 | Key</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Key</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.qipo.net/2018/01/27/java/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Key">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Key">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Java String类的基本特点</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-27T17:16:54+08:00">
                2018-01-27
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.3k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>java String类的基本特点</p>
<h1 id="String类的两种实例化方法"><a href="#String类的两种实例化方法" class="headerlink" title="String类的两种实例化方法"></a>String类的两种实例化方法</h1><p>几乎所有的项目开发过程之中都一定会有String类的使用，但是String类的定义有一些差别，在使用上是有一些注意事项的。</p>
<p>String可以采用直接赋值的方式进行处理，这一点感觉上是和我们的基本数据类型是非常相似的。</p>
<p>范例：直接赋值实例化对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//字符串的直接赋值</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String1</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		<span class="comment">//str是一个对象，那么‘hello’就应该保存在堆内存之中</span></span><br><span class="line">		String str = <span class="string">"hello"</span>;</span><br><span class="line">		System.out.println(str);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>但是String本身毕竟是一个类，既然是一个类，那么类中就一定会提供有构造方法，而在String类中我们恰好提供了以下的构造方法：</p>
<pre><code>构造：public String(String str);
</code></pre><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String2</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		<span class="comment">//该过程符合传统的类的实例化</span></span><br><span class="line">		String str = <span class="keyword">new</span> String (<span class="string">"hello"</span>);</span><br><span class="line">		System.out.println(str);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>暂时不考虑两者的区别以及使用，关键是要清楚String类现在提供有两种实例化对象的模式。</p>
<h1 id="字符串比较"><a href="#字符串比较" class="headerlink" title="字符串比较"></a>字符串比较</h1><p>如果说现在有两个int型的变量，判断其相等，我们可以用“==”完成。</p>
<p>范例：观察基本数据类型比较</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//基本数据类型的比较</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String3</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		<span class="keyword">int</span> x = <span class="number">10</span>;</span><br><span class="line">		<span class="keyword">int</span> y = <span class="number">10</span>;</span><br><span class="line">		System.out.println(x == y);<span class="comment">//true</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那么如果说在String类的对象上使用了<code>==</code>呢？</p>
<p>范例：观察在String上直接使用<code>==</code>比较</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//String类型使用==</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String4</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str1 = <span class="string">"hello"</span>;</span><br><span class="line">		String str2 = <span class="keyword">new</span> String (<span class="string">"hello"</span>);</span><br><span class="line">		System.out.println(str1 == str2);<span class="comment">//false</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>现在两个字符串的内容是相同的，而使用了“==”比较之后内容是不同的，如果想要得出结论需要进行我们的内存图分析。</p>
<p><img src="http://assets.qipo.net/String1.PNG" alt></p>
<p><code>==</code>本身是进行我们的数值比较的，但是如果用在了我们的对象之中，那么所比较的就应该是两个对象所保存的内存地址的数值，所以属于地址数值比较，而并没有比较对象的内容。</p>
<p>那么如果要进行内容的比较，则必须采用String类中的一个方法（暂时变形）：</p>
<pre><code>内容比较：`public Boolean equals(String str)`
</code></pre><p>实例：进行字符串内容比较</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//对象内容比较</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String5</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str1 = <span class="string">"hello"</span>;</span><br><span class="line">		String str2 = <span class="keyword">new</span> String (<span class="string">"hello"</span>);</span><br><span class="line">		System.out.println(str1.equals(str2));<span class="comment">//true</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>equals</code>和<code>==</code>的区别？</p>
</blockquote>
<blockquote>
<p><code>==</code>:进行的是我们的数值比较，比较的是我们两个字符串的内存地址数值；<br><code>equals</code>：进行的是我们String的内容进行比较；</p>
</blockquote>
<h1 id="字符串常量是String的匿名对象"><a href="#字符串常量是String的匿名对象" class="headerlink" title="字符串常量是String的匿名对象"></a>字符串常量是String的匿名对象</h1><p>在任何语言的底层上面都不可能有提供直接的字符串类型。现在所谓的字符串只是高级语言提供给用户方便开发的支持而已。所以在java里面本身也没有提供有字符串常量概念，所有使用<code>&quot;&quot;</code>定义的内容本质上来讲都是String类型的一个匿名对象。</p>
<p>范例：观察字符串操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String6</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str1 = <span class="string">"hello"</span>;</span><br><span class="line">		System.out.println(<span class="string">"hello"</span>.equals(str1));<span class="comment">//true</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那么在之前出现的<code>String str = &quot;hello&quot;</code>，本质上就是将一个匿名的String对象设置有名字，而且匿名对象一定保存在堆内存之中。</p>
<blockquote>
<p>提醒：在日后的开发过程之中，如果要判断用户输入的字符串是否等同于指定的字符串，那么一定要将字符串写到前面。</p>
</blockquote>
<ul>
<li>比较的操作方法之一：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String7</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String input = <span class="keyword">null</span>;</span><br><span class="line">		System.out.println(input.equals(<span class="string">"hello"</span>));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在进行数据输入接受的时候必须要考虑用户没有输入数据的问题，如果以上面的代码为例，用户没有输入的时候，那么一定会出现<code>Exception in thread &quot;main&quot; java.lang.NullPointerException</code>问题。</p>
<ul>
<li>任何字符串常量都是String匿名对象，所以该对象永远不可能为null；</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String7</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String input = <span class="keyword">null</span>;</span><br><span class="line">		System.out.println(<span class="string">"hello"</span>.equals(input));<span class="comment">//false</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那么以后在进行比较的时候，强烈建议如上的写法，把字符串写到前面。</p>
<h1 id="String两种实例化的区别"><a href="#String两种实例化的区别" class="headerlink" title="String两种实例化的区别"></a>String两种实例化的区别</h1><p>现在已经给出了String两种实例化的操作模式，那么在实际的开发之中，使用哪一种会更好，以及彼此之间的区别有哪些呢？</p>
<h2 id="采用直接赋值："><a href="#采用直接赋值：" class="headerlink" title="采用直接赋值："></a>采用直接赋值：</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//字符串的直接赋值</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String1</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		<span class="comment">//str是一个对象，那么‘hello’就应该保存在堆内存之中</span></span><br><span class="line">		String str = <span class="string">"hello"</span>;</span><br><span class="line">		System.out.println(str);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="http://assets.qipo.net/string2.PNG" alt></p>
<p>那么随后下面按照同样的模式继续进行新的字符串对象的创建</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String8</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str = <span class="string">"hello"</span>;</span><br><span class="line">		String str1 = <span class="string">"hello"</span>;</span><br><span class="line">		String str2 = <span class="string">"hello"</span>;</span><br><span class="line">		System.out.println( str == str1 );<span class="comment">//true</span></span><br><span class="line">		System.out.println( str1 == str2 );<span class="comment">//true</span></span><br><span class="line">		System.out.println( str == str2 );<span class="comment">//true</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="http://assets.qipo.net/string3.PNG" alt></p>
<p>以上是通过程序的运行结果来分析出的内存关系，但是从另一个方面来讲，为什么没有开辟新的堆内存空间呢?</p>
<p>String类的设计使用了一个共享的设计模式</p>
<p>在jvm的底层实际上会自动维护一个对象池（字符串对象池），如果现在使用了直接赋值的模式进行String类的实例化操作，那么该实例化对象（字符串）将自动保存到这个对象池之中，如果下次有人使用了直接赋值的模式声明了一个String类的对象，那么对象池之中有指定的内容，那么将直接进行引用，如果没有，将开辟新的字符串对象，而后将其保存在对象池之中以供下次使用。（所谓的对象池就是一个对象数组）</p>
<p>范例：观察与常量的比较</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//观察与常量的比较</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String9</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str = <span class="string">"hello"</span>;</span><br><span class="line">		System.out.println(<span class="string">"hello"</span> == str);<span class="comment">//true</span></span><br><span class="line">		System.out.println(<span class="string">"hello"</span> == <span class="string">"hello"</span>);<span class="comment">//true</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时返回的都是true，一方面是与共享设计有关，另一方面就是jdk版本不同也会存在若干差异。</p>
<h2 id="采用构造方法"><a href="#采用构造方法" class="headerlink" title="采用构造方法"></a>采用构造方法</h2><p>类对象使用构造方法进行实例化才属于我们的标准做法，那么来分析如下的一段程序：</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">String</span> <span class="built_in">str</span> = <span class="keyword">new</span> <span class="keyword">String</span> (<span class="string">"hello"</span>);</span><br></pre></td></tr></table></figure>
<p><img src="http://assets.qipo.net/string4.PNG" alt></p>
<p>那么通过分析首先可以确定一点的是，如果使用了构造方法将会开辟两块堆内存空间，并且有一块堆内存空间将会成为垃圾空间，除了这一缺点之外，实际上也会对我们的字符串共享产生问题。</p>
<p>范例：观察字符串共享问题</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String10</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str = <span class="keyword">new</span> String(<span class="string">"hello"</span>);</span><br><span class="line">		System.out.println(str == <span class="string">"hello"</span>);<span class="comment">//false</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那么这个时候并不表示不能够进入对象池保存，关键的问题是：需要手工来处理，在String类中有一个方法可以实现入池的操作：<code>public String intern()</code>;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String10</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str = <span class="keyword">new</span> String(<span class="string">"hello"</span>).intern();</span><br><span class="line">		System.out.println(str == <span class="string">"hello"</span>);<span class="comment">//true</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="http://assets.qipo.net/string5.PNG" alt></p>
<blockquote>
<p>请解释String对象实例化的两种区别？</p>
</blockquote>
<blockquote>
<p>直接赋值只会开辟一块堆内存空间，并且该字符串对象可以保存在对象池之中以供我们的下一次使用.<br>构造函数的模式会开辟两块堆内存空间，一块堆内存空间将成为垃圾，而且其字符串对象不会自动保存到我们的对象池之中，可以使用intern()方法手工入池。</p>
</blockquote>
<h1 id="字符串常量不可变更"><a href="#字符串常量不可变更" class="headerlink" title="字符串常量不可变更"></a>字符串常量不可变更</h1><p>所有的语言对于字符串的底层实现都是字符数组，数组的最大缺陷就是长度固定，所以在定义字符串常量的时候它的内容是不可能改变的。</p>
<p>范例：观察如下代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String11</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str = <span class="string">"hello"</span>;</span><br><span class="line">		str=str+<span class="string">"world"</span>;</span><br><span class="line">		System.out.println(str + <span class="string">"!!!"</span>);<span class="comment">//helloworld!!!</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以上字符串的变更是字符串对象的变更而不是，而并不是字符串的内容，以上的代码执行操作如下：</p>
<p><img src="http://assets.qipo.net/string6.PNG" alt></p>
<p>可以发现字符串上没有发生我们的任何的变化，但是字符串对象的引用却一直在改变，而且会形成大量的垃圾，正是因为String的这个特点，所以如下的代码不应该在你的开发中出现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在你的开发之中不应该出现</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String12</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">		String str = <span class="string">"hello"</span>;</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span> ;i&lt; <span class="number">100</span> ;i++) &#123;</span><br><span class="line">			str+=i;</span><br><span class="line">		&#125;</span><br><span class="line">		System.out.println(str);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果说现在很多用户都使用了同样的操作，那么产生的垃圾数量就相当可观了。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><ol>
<li>字符串的使用就采用我们的直接赋值的模式</li>
<li>字符串的比较就是用我们的equals()方法实现</li>
<li>字符串没事别改变太多</li>
</ol>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Key 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Key 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag"># Java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/03/java/" rel="next" title="Java数组的定义与使用">
                <i class="fa fa-chevron-left"></i> Java数组的定义与使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/31/java/" rel="prev" title="Java String类的常用方法">
                Java String类的常用方法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Key">
            
              <p class="site-author-name" itemprop="name">Key</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">107</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/keyarea" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:wxkayle@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#String类的两种实例化方法"><span class="nav-number">1.</span> <span class="nav-text">String类的两种实例化方法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#字符串比较"><span class="nav-number">2.</span> <span class="nav-text">字符串比较</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#字符串常量是String的匿名对象"><span class="nav-number">3.</span> <span class="nav-text">字符串常量是String的匿名对象</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#String两种实例化的区别"><span class="nav-number">4.</span> <span class="nav-text">String两种实例化的区别</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#采用直接赋值："><span class="nav-number">4.1.</span> <span class="nav-text">采用直接赋值：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#采用构造方法"><span class="nav-number">4.2.</span> <span class="nav-text">采用构造方法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#字符串常量不可变更"><span class="nav-number">5.</span> <span class="nav-text">字符串常量不可变更</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Key</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">190.8k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
